﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Pheonix.Fashionzoomer.DAL;
using Pheonix.CodeLibrary.Web;
using Pheonix.CodeLibrary.Data;
using Pheonix.Fashionzoomer.Entity.SqlServer2000;
using System.Text;
using Pheonix.CodeLibrary;
using System.IO;
using Pheonix.Fashionzoomer.BLL;

public partial class page_private_admin_productdetail : AdminBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Title = SiteName + " - Product Details [ Admin ]";
        LoadScript();
        if (!IsPostBack)
        {
            try
            {
                BindControls();

                if (Request.QueryString["id"] != null)
                {
                    int id = 0;
                    if (int.TryParse(Request.QueryString["id"], out id))
                        LoadEditData(id);
                }
            }
            catch (Exception ex)
            {
                uccResponseMessage.SetFailMessage("There was a problem in loading the page");
            }
        }
        if (Request.QueryString["id"] == null)
            lblTitle.Text = "Add a new product";
        else
            lblTitle.Text = "Update product";
    }

    protected void Shop_Change(object sender, EventArgs e)
    {
        if (ndlShop.SelectedValue != "-1")
        {
            ndlCategory.DataSource = CustomCommand.GetShopCategoryByShopId(int.Parse(ndlShop.SelectedValue));
            ndlCategory.DataBind();
            ndlCategory.Items.Insert(0, new ListItem("Select", "-1"));
        }
        else
        {
            ndlCategory.Items.Clear();
            ndlCategory.Items.Insert(0, new ListItem("Select", "-1"));
        }
    }

    private void BindControls()
    {
        lblProductCode.Text = "Auto generated - can be viewed after creating product";

        tbxAvailableFrom.Attributes.Add("datepicker", "true");
        tbxAvailableFrom.Attributes.Add("datepicker_format", "MM-DD-YYYY");

        if (!IsPostBack)
            imgDefaultImage.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/image/imageNA.gif";

        ndlShop.DataSource = CustomCommand.GetShopForDropdown();
        ndlShop.DataBind();
        ndlShop.Items.Insert(0, new ListItem("Select", "-1"));

        ndlCategory.Items.Insert(0, new ListItem("Select", "-1"));
    }

    private void LoadScript()
    {
        if (!ClientScript.IsClientScriptIncludeRegistered("datepickercontrol"))
            ClientScript.RegisterClientScriptInclude("datepickercontrol", "../thirdparty/datepickercontrol/datepickercontrol.js");
    }

    private string GenerateProductCode(int productId)
    {
        StringBuilder productCode = new StringBuilder("FZP");
        productCode.Append(productId.ToString().PadLeft(8,'0'));
        return productCode.ToString().ToUpper();
    }

    private void LoadEditData(int editDataId)
    {
        Product editProduct = null;
        if (editDataId != 0)
            editProduct = Product.GetProductById(editDataId);
        if (editProduct != null)
        {
            tbxProductName.Text = editProduct.ProductName;
            fckProductDescription.Value = editProduct.ProductDescription;
            imgDefaultImage.ImageUrl = editProduct.DefaultImageUrl.Replace("max","thumb");
            ddlForMale.SelectedValue = editProduct.ForMale.ToString();
            
            cbxIsFeatured.Checked = editProduct.IsFeatured;
            ndlShop.SelectedValue = editProduct.ShopId.ToString();

            if (ndlShop.SelectedValue != "-1")
            {
                ndlCategory.DataSource = CustomCommand.GetShopCategoryByShopId(int.Parse(ndlShop.SelectedValue));
                ndlCategory.DataBind();
                ndlCategory.Items.Insert(0, new ListItem("Select", "-1"));
            }

            ndlCategory.SelectedValue = editProduct.CategoryId.ToString();

            lblProductCode.Text = editProduct.ProductCode;
            tbxPriceLow.Text = editProduct.PriceLow.ToString();
            tbxPriceHigh.Text = editProduct.PriceHigh.ToString();
            tbxStockAmount.Text = editProduct.StockAmount.ToString();
            tbxAvailableFrom.Text = editProduct.AvailableFrom.ToShortDateString();
            fckSpecialOffer.Value = editProduct.SpecialOffer;
            tbxPriority.Text = editProduct.Priority.ToString();
            tbxKeywords.Text = editProduct.Keywords;
        }
    }

    private string UploadImage(string productCode)
    {
        if (!string.IsNullOrEmpty(fluDefaultImage.FileName))
        {
            string imagePath = null;
            string tempImagePath = (string)(new AppSettingsReader().GetValue("TempPath", typeof(string)));
            string mimeType = fluDefaultImage.PostedFile.ContentType;

            if (mimeType == "image/jpeg" || mimeType == "image/gif" || mimeType == "image/png")
            {
                string tempFileName = tempImagePath + Guid.NewGuid() +
                    Path.GetExtension(fluDefaultImage.FileName);
                fluDefaultImage.SaveAs(MapPath(tempFileName));

                imagePath = ProductManager.UploadProductImage(tempFileName, productCode);
                return imagePath;
            }
            else
                uccResponseMessage.SetFailMessage("Only JPG, GIF, PNG image allowed");
        }
        return null;
    }

    protected void Save_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            int productId = 0;
            Product editProduct = null;

            if (Request.QueryString["id"] != null)
            {
                if (int.TryParse(Request.QueryString["id"], out productId))
                {
                    editProduct = Product.GetProductById(productId);
                }
            }

            string productName = Utility.FilterInputText(tbxProductName.Text);
            if (!string.IsNullOrEmpty(productName))
            {
                int productCategoryId = 0;
                if (int.TryParse(ndlCategory.SelectedValue, out productCategoryId))
                {
                    string productDescription = fckProductDescription.Value;

                    bool forMale = true;
                    if(ddlForMale.SelectedValue != null)
                        bool.TryParse(ddlForMale.SelectedValue, out forMale);

                    int shopId = -1;
                    if (ndlShop.SelectedValue != null)
                        int.TryParse(ndlShop.SelectedValue, out shopId);

                    double minPrice = 0;
                    double.TryParse(tbxPriceLow.Text, out minPrice);

                    double maxPrice = 0;
                    double.TryParse(tbxPriceHigh.Text, out maxPrice);

                    int stockAmount = 0;
                    int.TryParse(tbxStockAmount.Text, out stockAmount);

                    DateTime availableFrom = DateTime.Now;
                    DateTime.TryParse(tbxAvailableFrom.Text, out availableFrom);

                    string specialOffer = fckSpecialOffer.Value;

                    int priority = 0;
                    string keywords = Utility.FilterInputText(tbxKeywords.Text);

                    if (editProduct != null)
                    {
                        if (editProduct.CategoryId != productCategoryId || editProduct.ShopId != shopId)
                        {
                            CustomCommand.DecreaseCategoryItemCount(editProduct.CategoryId,shopId);
                            CustomCommand.IncreaseCategoryItemCount(productCategoryId, shopId);
                        }

                        editProduct.ProductName = productName;

                        string newImageUrl = UploadImage(editProduct.ProductCode);
                        if (!string.IsNullOrEmpty(newImageUrl))
                            editProduct.DefaultImageUrl = newImageUrl;
                        
                        if(!string.IsNullOrEmpty(editProduct.DefaultImageUrl))
                            editProduct.ImagePath = editProduct.DefaultImageUrl.Substring(0, 
                                editProduct.DefaultImageUrl.LastIndexOf('/'));
                        
                        editProduct.AvailableFrom = availableFrom;
                        editProduct.CategoryId = productCategoryId;
                        editProduct.ForMale = forMale;
                        editProduct.IsFeatured = cbxIsFeatured.Checked;
                        editProduct.LastUpdate = DateTime.Now;
                        editProduct.PriceHigh = (decimal)maxPrice;
                        editProduct.PriceLow = (decimal)minPrice;
                        editProduct.Priority = priority;
                        editProduct.ProductDescription = productDescription;
                        editProduct.ShopId = shopId;
                        editProduct.SpecialOffer = specialOffer;
                        editProduct.StockAmount = stockAmount;
                        editProduct.Keywords = keywords;

                        if (editProduct.Save())
                        {
                            uccResponseMessage.SetSuccessMessage("Product successfuly updated");
                            LoadEditData(productId);
                        }
                        else
                            uccResponseMessage.SetFailMessage("Could not update product");
                    }
                    else
                    {
                        string productCode = string.Empty;
                        string imagePath = string.Empty;
                        string imageFolder = string.Empty;

                        int newProductId = Product.CreateNewProduct(productName, productDescription,
                            imageFolder, imagePath, forMale, productCategoryId,
                            cbxIsFeatured.Checked,0,shopId,productCode,DateTime.Now,DateTime.Now,(decimal)minPrice,
                            (decimal)maxPrice, stockAmount, availableFrom, specialOffer, 0, 0, priority, keywords);

                        productCode = GenerateProductCode(newProductId);
                        imagePath = UploadImage(productCode);
                        if (!string.IsNullOrEmpty(imagePath))
                            imageFolder = imagePath.Substring(0, imagePath.LastIndexOf('/'));

                        bool updateSuccess = Product.UpdateProduct(newProductId, productName, productDescription,
                            imageFolder, imagePath, forMale, productCategoryId, cbxIsFeatured.Checked, 0, shopId,
                            productCode, DateTime.Now, DateTime.Now, (decimal)minPrice, (decimal)maxPrice, stockAmount, 
                            availableFrom, specialOffer, 0, 0, priority, keywords);

                        if (updateSuccess)
                        {
                            CustomCommand.IncreaseCategoryItemCount(productCategoryId, shopId);
                            uccResponseMessage.SetSuccessMessage("Product successfuly created");
                            LoadEditData(newProductId);
                        }
                        else
                            uccResponseMessage.SetFailMessage("Could not create product");
                    }
                }
                else
                    uccResponseMessage.SetFailMessage("You must select a valid category");
            }
            else
                uccResponseMessage.SetFailMessage("Product name is invalid");
        }
        else
            uccResponseMessage.SetFailMessage("Could not save because of invalid data");
    }

    protected void Back_Click(object sender, EventArgs e)
    {
        Response.Redirect("productlist.aspx");
    }
}
